package com.example.consumer.consume;

import com.alibaba.fastjson.JSON;
import com.example.consumer.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 这里有坑:
 * 因为pub/sub端并没有公用实体,pub端序列化为com.pub.A,sub端没有这个类 会造成反序列化失败、classNotFoundException
 * 方案一: 公用一个实体类
 * 方案二: 发送端将实体转为JSON string,sub端再将json转换为实体
 * @author shuc001
 * @Date 2018/9/27 下午2:55
 */
@Component
public class AckConsumer {


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "ack_q",durable = "true"),
            exchange = @Exchange(value = "ack_ex",type = "topic"),
            key = "ack.#"
    ))
    @RabbitHandler
    public void receive(@Payload String json, @Headers Map<String,Object> headers, Channel channel) throws IOException {
        System.out.println("ack model "+ JSON.parseObject(json,Order.class));
        channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG),true);
    }
}
